package com.baosight.risk.common.quartz;

import com.baosight.risk.api.fltd.FltdProcessService;
import com.baosight.risk.api.zbaa.IZbaaTargetService;
import com.baosight.risk.common.aspects.factory.AsyncFactory;
import com.baosight.risk.common.bean.BeanUtils;
import com.baosight.risk.common.manager.AsyncManager;
import com.baosight.risk.common.utils.IDGenerator;
import com.baosight.risk.mapper.zbaa.ZbaaTargetValueMapper;
import com.baosight.risk.service.system.entity.SysOperLog;
import com.baosight.risk.service.zbaa.entity.ZbaaTarget;
import com.baosight.risk.service.zbaa.entity.ZbaaTargetValue;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @description: 宝特长材
 * @Author: LiuHaoNan
 * @Date:
 */
@Slf4j
@Component("baoTeTargetTask")
public class BaoTeTargetTask {
    @Autowired
    ZbaaTargetValueMapper zbaaTargetValueMapper;

    @Autowired
    private FltdProcessService fltdProcessService;

    @Autowired
    private IZbaaTargetService targetService;

    public void testParams(String params, String jobId) throws Exception {
        getDataByDay(params, jobId);
    }

    //通过表里最新的数据判断是否需要录入新的数据
    //如果表里最新的数据是当前日期的上个季度的   如果是就跳过数据录入   如果不是  则开始遍历目标目录的所有文件,读取数据
    /**
     * 文件里的数据是按月的 但是数据录入的时候是要按季度的   所以只取当前时间上个季度的
     * @param params
     * @param jobId
     */
    public void getDataByDay(String params,String jobId) throws Exception {
        List<SysOperLog> logs = new ArrayList<>();
        Exception error = null;
        //得出当前日期的上个季度的时间例(2020Q1)

        String lastQuarter = getlastQuarter();

        try {
            List<ZbaaTargetValue> lastZbaaTargetInfo = zbaaTargetValueMapper.getLastZbaaTargetInfo("ZBN0139", "H", null, null, "1");
            if (lastZbaaTargetInfo.size()!=0){
                ZbaaTargetValue value = lastZbaaTargetInfo.get(0);
                String periodNo = value.getPeriodNo();
                if (!periodNo.equals(lastQuarter)){//如果表数据的最后一条记录   不是  当前日期的上个季度那么就进行数据读取
                    Map<String,String> map = readTextAndGetTasks();
                    //根据上个季度的日期  求出上个季度的三个月份  例:202004,202005,202006
                    String[] lastQuarterAboutMonth = getLastQuarterAboutMonth(lastQuarter);
                    int count = 0;
                    double bangYi = 0;
                    double xianCai = 0;
                    for (int i = 0;i < lastQuarterAboutMonth.length;i++){
                        if (map.containsKey(lastQuarterAboutMonth[i] + "棒一")){
                            bangYi = Double.parseDouble(bangYi + map.get(lastQuarterAboutMonth[i] + "棒一"));
                            xianCai = Double.parseDouble(xianCai + map.get(lastQuarterAboutMonth[i] + "线材"));
                        }
                        count++;
                    }
                    if (count == 3){//表示三个月份的都齐全了
                        String bangYiTargetNo = "ZBN0138";
                        String xianCaiTargetNo = "ZBN0139";
                        for (int i = 0;i < 2 ;i++){
                            String targetNo;
                            Double targetValue = null;
                            if (i == 0) {
                                targetNo = bangYiTargetNo;
                                targetValue = bangYi;
                            }
                            else{
                                targetNo = xianCaiTargetNo;
                                targetValue = xianCai;
                            }

                            //单位换算成万吨
                            targetValue = (double) Math.round(targetValue * 100) / 100;
                            ZbaaTarget target = targetService.getTargetByTargetNo(targetNo);
                            ZbaaTargetValue zbaaTargetValue = new ZbaaTargetValue();
                            BeanUtils.copyBeanProp(zbaaTargetValue,target);
                            BeanUtils.initBean(zbaaTargetValue);
                            BeanUtils.initExt(zbaaTargetValue);
                            zbaaTargetValue.setTargetValue(targetValue.toString());
                            zbaaTargetValue.setPeriodNo(lastQuarter);
                            zbaaTargetValue.setAcctYear(lastQuarter.substring(0,4));
                            zbaaTargetValue.setId(IDGenerator.getIdStr());

                            logs.add(fltdProcessService.getLog("宝特长材定时任务实行成功", 0, "", jobId));
                        }

                    }else{
                        log.error("宝特长材定时任务实行失败");
                        logs.add(fltdProcessService.getLog("宝特长材定时任务实行失败", 1, "月份数据不齐全", jobId));
                    }

//                    if (zbaaTargetValue!=null){
//                        zbaaTargetValueMapper.insert(zbaaTargetValue);
//                        logs.add(fltdProcessService.getLog("获取汽车板销量数据定时任务执行成功", 0, "", jobId));
//                    }
                }
            }




        }catch (Exception e){
            error = e;
            log.error("获取汽车板销量数据异常！");
            logs.add(fltdProcessService.getLog("获取汽车板销量数据定时任务执行失败", 1, e.getMessage(), jobId));
        }

        // 保存日志到数据库
        AsyncManager.me().execute(AsyncFactory.batchRecordOper(logs));
        if (error != null) {
            throw error;
        }
    }


    public Map<String,String> readTextAndGetTasks() throws Exception {

        Map<String, String> map = new HashMap<>();
        //先遍历目录下的txt文件名称,然后追加遍历读取文件数据
        String folderPath = "/autosys/JV/ZQ";
        File dir = new File(folderPath);
        String[] children = dir.list();
        if (children == null) {
            System.out.println( "目录不存在或它不是一个目录");
            throw new Exception("目录不存在或它不是一个目录");
        }
        else {
            for (int i=0; i< children.length; i++) {
                String filename = children[i];
                System.out.println(filename);

                FileInputStream filestream=new FileInputStream(folderPath + "/" + filename);
                byte[] b = new byte[3];
                filestream.read(b);
                String ecode="gbk";
                if (b[0] == -17 && b[1] == -69 && b[2] == -65){
                    ecode="utf-8";
                }
                InputStreamReader readStream=new InputStreamReader(filestream,ecode);
                BufferedReader reader=new BufferedReader(readStream);

                String temp=null;
                int line=0;//行号
                boolean xianCaiFlag = false;
                while((temp=reader.readLine())!=null){
                    line++;
                    if (line == 10 || line == 11){
                        String[] split = temp.split(";");
                        if (!xianCaiFlag){
                            //System.out.println(line+"棒一"+temp);
                            map.put(split[0].trim()+"棒一",split[2].trim());
                            xianCaiFlag = true;

                        }else {
                            map.put(split[0].trim()+"线材",split[2].trim());
                            //System.out.println(line+"线材"+temp);
                        }
                    }
                }

                long endTime=System.currentTimeMillis(); //获取结束时间
                if(readStream!=null){
                    readStream.close();
                }
                if(reader!=null){
                    reader.close();
                }

            }
        }

        return map;
    }


    /**
     * 判断表里取出来的数据是否是当前日期上个季度的
     * @param periodNo
     * @return
     */
    public Boolean checkQ(String periodNo) {
        //算出当前日期的上个季度
        Date nowDate = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");
        //当前日期
        String nowFormat = formatter.format(nowDate);
        nowFormat = nowFormat.substring(0,4) + nowFormat.substring(5,7);

        String nowYear = nowFormat.substring(0, 4);
        String nowMonth = nowFormat.substring(4, 6);
        String lastQuarter = "";
        switch (nowMonth) {
            case "01":
            case "02":
            case "03":
                lastQuarter = "Q4";
                nowYear = (Integer.parseInt(nowYear) - 1) + "";
                break;
            case "04":
            case "05":
            case "06":
                lastQuarter = "Q1";
                break;
            case "07":
            case "08":
            case "09":
                lastQuarter = "Q2";
                break;
            case "10":
            case "11":
            case "12":
                lastQuarter = "Q3";
                break;
        }
//        String taskYear = periodNo.substring(0, 4);
//        String taskQuarter = periodNo.substring(4, 6);

        return periodNo.equals(nowYear+lastQuarter);
    }

    /**
     * 求出当前日期上个季度的字符串
     * @param
     * @return
     */
    public String getlastQuarter() {
        //算出当前日期的上个季度
        Date nowDate = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");
        //当前日期
        String nowFormat = formatter.format(nowDate);
        nowFormat = nowFormat.substring(0,4) + nowFormat.substring(5,7);

        String nowYear = nowFormat.substring(0, 4);
        String nowMonth = nowFormat.substring(4, 6);

//        nowYear = "2020";
//        nowMonth = "04";
        String lastQuarter = "";
        switch (nowMonth) {
            case "01":
            case "02":
            case "03":
                lastQuarter = "Q4";
                nowYear = (Integer.parseInt(nowYear) - 1) + "";
                break;
            case "04":
            case "05":
            case "06":
                lastQuarter = "Q1";
                break;
            case "07":
            case "08":
            case "09":
                lastQuarter = "Q2";
                break;
            case "10":
            case "11":
            case "12":
                lastQuarter = "Q3";
                break;
        }
//        String taskYear = periodNo.substring(0, 4);
//        String taskQuarter = periodNo.substring(4, 6);

        return nowYear+lastQuarter;
    }

    public String[] getLastQuarterAboutMonth(String lastQuarter){
        String quarter = lastQuarter.substring(5, 6);
        String year = lastQuarter.substring(0, 4);
        switch (quarter) {
            case "1":
                return new String[]{year+"01",year+"02",year+"03"};
            case "2":
                return new String[]{year+"04",year+"05",year+"06"};
            case "3":
                return new String[]{year+"07",year+"08",year+"09"};
            case "4":
                return new String[]{year+"10",year+"11",year+"12"};
        }
        return null;
    }

    public static void main(String[] args) {
//        BaoteTargetTask baoteTargetTask = new BaoteTargetTask();
//        String s = baoteTargetTask.getlastQuarter();
//        System.out.println(s);
        double d = 114.149;
        d = (double) Math.round(d * 100) / 100;
        System.out.println(d);
    }

}
